package com.geektime.prepare_week2_servletJNDI.listener;

import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 描述
 *
 * @author xgq
 * @version 1.0
 * @date 2021/06/17 15:06:14
 */

@WebListener
public class DBConnectionInitListener implements ServletContextListener {



    //
    private final Logger logger =Logger.getLogger(DBConnectionInitListener.class.getName());

   /* @Resource(name = "jdbc/UserPlatformDataSource")
    private DataSource dataSource;*/
    @Override
    public void contextInitialized(ServletContextEvent sce) {
       // System.out.println("开始测试连接方法");
        logger.info("Test connect start");
        getConnection();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }



    /*public Connection getConnection() {
        // 依赖查找
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
        if (connection != null) {
            logger.log(Level.INFO, "获取 JNDI 数据库连接成功！");
        }
        return connection;
    }*/

    public Connection getConnection() {
        Context initCtx;
        Context envCtx;
        DataSource ds;
        // 依赖查找
        Connection connection = null;
        try {
            /*Hashtable  htEnv = new Hashtable();
            htEnv.put(Context.INITIAL_CONTEXT_FACTORY,
                    "weblogic.jndi.WLInitialContextFactory");
            htEnv.put(Context.PROVIDER_URL,
                    "t3://127.0.0.1:7001");*/

            initCtx = new InitialContext();

            /*
             * 描述:
             *      将InitialContext其配置为最初部署的Web应用程序，并可供Web应用程序组件使用（用于只读访问）。
             *      所有已配置的条目和资源都放置在java:comp/env JNDI名称空间的一部分中.
             */

            envCtx = (Context) initCtx.lookup("java:comp/env");
            ds = (DataSource) envCtx.lookup("jdbc/Derby");
            connection = ds.getConnection();
        } catch (NamingException | SQLException e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
        if (connection != null) {
            System.out.println("JNDI connect success !");
           // logger.log(Level.INFO, "获取 JNDI 数据库连接成功！");
        }else{
            System.out.println(" JNDI connect fail !");
           // logger.info("获取 JNDI 数据库连接失败！");
        }
        return connection;
    }

}
